package is.glif.fenius.webui.servlet;

import is.glif.fenius.webui.client.FileCredentialsProvider;
import is.glif.fenius.webui.client.Requester;
import is.glif.fenius.webui.common.WebUIException;
import is.glif.fenius.webui.topo.FileNetworkProvider;
import is.glif.fenius.ws.connection.gen.Avp;
import is.glif.fenius.ws.connection.gen.Reservation;
import is.glif.fenius.ws.connection.gen.Vertex;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ListServlet  extends HttpServlet {
    public static final long serialVersionUID = 1L;
    private static Logger log = Logger.getLogger(ListServlet.class);
    private static HashMap<String, List<Reservation>> resvsByNetwork;
    private static Long lastUpdated = 0L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter pw = response.getWriter();

        Long now = new Date().getTime();
        Long age = now - lastUpdated;
        
        try {
            JSONArray arr = FileNetworkProvider.getInstance().getNetworks("*");
            ArrayList<String> networkIds = new ArrayList<String>();
            
            int len = arr.length();
            for (int i = 0; i < len; i++) {
                JSONObject obj = arr.getJSONObject(i);
                String networkId = obj.getString("id");
                String cred = null;
                try {
                    cred = FileCredentialsProvider.getInstance().getURL(networkId);
                } catch (JSONException ex) {
                    //
                }
                if (cred != null && cred.trim().length() > 0 ) {
                    networkIds.add(networkId);
                }
            }
                        
            if (age > 60000) {
                Requester req = Requester.getInstance();
                resvsByNetwork = req.listAllCurrent(networkIds);
                lastUpdated = now;
            } else {
                log.info("using cached version from "+age+" ms ago");
            }
            
            JSONArray result = new JSONArray();
            for (String networkId : networkIds) {
                if (resvsByNetwork.get(networkId) != null) {
                    for (Reservation resv : resvsByNetwork.get(networkId)) {
                        JSONArray composite = new JSONArray();
                        result.put(composite);
                        JSONObject resvJSON= new JSONObject();
                        composite.put(resvJSON);
                        resvJSON.put("network", networkId);
                        resvJSON.put("resvId", resv.getReservationId());
                        resvJSON.put("resvStatus", resv.getReservationStatus());
                        resvJSON.put("opStatus", resv.getActivationStatus());
                        Date start = resv.getSchedule().getAdvance().getStart().toGregorianCalendar().getTime();

                        String up = start.toString();
                        String dn = "";
                        if (resv.getSchedule().getAdvance().getEnd() != null) {
                            dn = resv.getSchedule().getAdvance().getEnd().toGregorianCalendar().getTime().toString();
                        } else {
                            Integer dur = resv.getSchedule().getAdvance().getDuration();
                            Long ms = start.getTime();
                            Long endms = ms + 1000*dur;
                            Date end = new Date(endms);
                            dn = end.toString();
                        }
                        resvJSON.put("up", up);
                        resvJSON.put("dn", dn);
                        resvJSON.put("bandwidth", resv.getTopology().getEdges().get(0).getBandwidth());
                        String aUrn = resv.getTopology().getVertices().get(0).getResourceId();
                        String zUrn = resv.getTopology().getVertices().get(1).getResourceId();
                        String aVlan = "";
                        String zVlan = "";
                        for (Avp avp : resv.getTopology().getVertices().get(0).getTechParams().getAvp()) {
                            if (avp.getAttrName().equals("eth.vlanTag")) {
                                aVlan = avp.getAttrVal();
                            }
                        }
                        for (Avp avp : resv.getTopology().getVertices().get(0).getTechParams().getAvp()) {
                            if (avp.getAttrName().equals("eth.vlanTag")) {
                                zVlan = avp.getAttrVal();
                            }
                        }
                        
                        resvJSON.put("a", aUrn);
                        resvJSON.put("z", zUrn);
    
                        resvJSON.put("aVlan", aVlan);
                        resvJSON.put("zVlan", zVlan);
                        
                    }
                }
            }
            
            
            
            String output = result.toString(2);
            pw.println(output);
            // System.out.println(output);
        } catch (JSONException e) {
            log.error(e);
            pw.println("Error: " + e.getMessage());
            e.printStackTrace();
        } catch (WebUIException e) {
            log.error(e);
            pw.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
     }

}
